package com.ccg.scheduled;

import com.ccg.entity.Date_Rt_Number;
import com.ccg.entity.RoomType;
import com.ccg.service.Date_Rt_NumberService;
import com.ccg.service.RoomTypeService;
import com.ccg.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

@Component
public class DateRtNumber {

    @Autowired
    Date_Rt_NumberService date_rt_numberService;
    @Autowired
    RoomTypeService roomTypeService;

    //每天刷新订房表
    @Scheduled(cron = "0 0 0 * * ?")
    public void refreshDateRtNumber() throws ParseException {
        Date_Rt_Number date_rt_number = new Date_Rt_Number();
        //获取所有的房间类型
        List<RoomType> list = roomTypeService.findAllTypeName();
        if(list.size()>0) {
            //从未来的第十五天开始初始化订房表房间数量
            Date date = DateUtil.dateAddOrMinus(new Date(), 14);
            String dateStr = DateUtil.getCurrentTime(date, "yyyy-MM-dd");
            for (int i = 1; i <= 15; i++) {
                for (RoomType rt : list) {
                    //判断该房间类型是否存在房间
                    if (rt.getNumber() != 0) {
                        date_rt_number.setDate(dateStr);
                        date_rt_number.setNumber(rt.getNumber());
                        date_rt_number.setRt_id(rt.getRt_id());
                        try {
                            date_rt_numberService.refresh(date_rt_number);
                        }catch (DuplicateKeyException e){
                            System.out.println("遇到主键重复,房间初始化完成;");
                        }
                        System.out.println("初始化" + dateStr + "的订房数量成功！");
                    }
                }
                //后退一天
                date = DateUtil.dateAddOrMinus(DateUtil.timeFormat(dateStr), -1);
                dateStr = DateUtil.getCurrentTime(date, "yyyy-MM-dd");
            }
        }

    }
}
